package com.zhongge.gui;

import com.zhongge.book.Book;
import com.zhongge.book.BookList;
import com.zhongge.operations.AddBook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 新增图书对话框
 */
public class AddBookDialog extends JDialog {
    private BookList bookList;
    private JTextField nameField;
    private JTextField authorField;
    private JTextField priceField;
    private JTextField typeField;
    private boolean addCompleted = false;
    
    public AddBookDialog(Frame parent, BookList bookList) {
        super(parent, "新增图书", true);
        this.bookList = bookList;
        initUI();
        setSize(400, 350);
        setLocationRelativeTo(parent);
    }
    
    /**
     * 初始化界面
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 创建表单面板，使用GridBagLayout进行精确布局
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        // 书名
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("书名:"), gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        nameField = new JTextField(20);
        formPanel.add(nameField, gbc);
        
        // 作者
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        formPanel.add(new JLabel("作者:"), gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        authorField = new JTextField(20);
        formPanel.add(authorField, gbc);
        
        // 价格
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        formPanel.add(new JLabel("价格:"), gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        priceField = new JTextField(20);
        formPanel.add(priceField, gbc);
        
        // 类型
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        formPanel.add(new JLabel("类型:"), gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        typeField = new JTextField(20);
        formPanel.add(typeField, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        JButton addButton = new JButton("添加");
        JButton cancelButton = new JButton("取消");
        
        addButton.addActionListener(new AddListener());
        cancelButton.addActionListener(e -> dispose());
        
        buttonPanel.add(addButton);
        buttonPanel.add(cancelButton);
        
        // 添加到主面板
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    /**
     * 添加按钮监听器
     */
    private class AddListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取输入值
            String name = nameField.getText().trim();
            String author = authorField.getText().trim();
            String priceText = priceField.getText().trim();
            String type = typeField.getText().trim();
            
            // 验证输入
            if (name.isEmpty() || author.isEmpty() || priceText.isEmpty() || type.isEmpty()) {
                JOptionPane.showMessageDialog(AddBookDialog.this, 
                        "请填写所有字段", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            int price;
            try {
                price = Integer.parseInt(priceText);
                if (price <= 0) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(AddBookDialog.this, 
                        "请输入有效的价格", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 检查图书是否已存在
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                if (name.equals(bookList.getBook(i).getName())) {
                    JOptionPane.showMessageDialog(AddBookDialog.this, 
                            "图书《" + name + "》已存在", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }
            
            // 调用原有AddBook实现添加功能
            AddBook addOperation = new AddBook();
            
            // 创建自定义输入流模拟控制台输入
            ConsoleInputSimulator inputSimulator = new ConsoleInputSimulator();
            inputSimulator.provideInput(name + "\n" + author + "\n" + price + "\n" + type + "\n");
            inputSimulator.startSimulation();
            
            try {
                // 执行添加操作
                addOperation.work(bookList);
                addCompleted = true;
                JOptionPane.showMessageDialog(AddBookDialog.this, 
                        "图书《" + name + "》添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(AddBookDialog.this, 
                        "添加失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                inputSimulator.stopSimulation();
            }
        }
    }
    
    /**
     * 判断添加是否完成
     */
    public boolean isAddCompleted() {
        return addCompleted;
    }
    
    /**
     * 控制台输入模拟工具类
     */
    private class ConsoleInputSimulator {
        private java.io.ByteArrayInputStream inBuffer;
        private java.io.InputStream originalIn;
        
        public void provideInput(String input) {
            inBuffer = new java.io.ByteArrayInputStream(input.getBytes());
        }
        
        public void startSimulation() {
            originalIn = System.in;
            System.setIn(inBuffer);
        }
        
        public void stopSimulation() {
            System.setIn(originalIn);
        }
    }
}